package com.aide.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.aide.security.auth.AideRead;

public class AideSNManager {

	private static final Logger logger = Logger.getLogger(AideSNManager.class);
	private static String sn = "";
	private static String user = "";
	private static String basepath = "";

	public AideSNManager() {
	}

	public static String getSn() {
		return sn;
	}

	public static void setSn(String sn) {
		AideSNManager.sn = sn;
		save();
	}

	public static String getUser() {
		return user;
	}

	public static void setUser(String user) {
		AideSNManager.user = user;
		save();
	}

	public static boolean isAuthorized() {
		if (sn == null || sn.equals(""))
			load();
		if (user != null && !user.equals("") && sn != null && !sn.equals("")
				&& AideRead.v(user, sn)) {
			return true;
		} else {
			logger.error("授权过期或未授权");
			return false;
		}
	}

	public static String mac() {
		return AideRead.mac(user);
	}

	public static String authorized() {
		return AideRead.vi(user, sn);
	}

	public static void init(String basepath) {
		AideSNManager.basepath = basepath;
		load();
	}

	public static boolean save() {
		InputStream is;
		OutputStream os;
		is = null;
		os = null;
		File snF;
		Properties config;
		snF = getSNFile();
		config = new Properties();
		if (snF == null) {
			return false;
		}
		try {
			is = new FileInputStream(snF);
			config.load(is);
			os = new FileOutputStream(snF);
			config.put("sn", sn);
			config.put("user", user);
			config.store(os, "");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				try {
					os.close();
				} catch (IOException e) {
				}
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}
		return false;
	}

	public static boolean putPorpValue(String porp_name, String key,
			String value, String dir) {
		String path;
		InputStream is = null;
		OutputStream os = null;
		path = (new StringBuilder(String.valueOf(fixedDir(dir))))
				.append(File.separator).append(porp_name).toString();
		File snF = new File(path);
		if (!snF.exists() || !snF.isFile()) {
			logger.warn((new StringBuilder(String.valueOf(path))).append(
					"不存在，系统初始化。").toString());
			try {
				snF.createNewFile();
			} catch (IOException e) {
				return false;
			}
		}
		try {
			is = new FileInputStream(path);
			Properties config = new Properties();
			config.load(is);
			config.put(key, value);
			config.store(os, "");
			return true;
		} catch (IOException e) {
			logger.error((new StringBuilder("读取")).append(path).append("文件失败！")
					.append(e.getMessage()).toString());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		return false;

	}

	public static String getPorpValue(String porp_name, String key, String dir) {
		String path = "";
		InputStream is = null;
		try {
			path = (new StringBuilder(String.valueOf(fixedDir(dir))))
					.append(File.separator).append(porp_name).toString();
			String s = null;
			is = new FileInputStream(path);
			Properties config = new Properties();
			config.load(is);
			Object obj = config.get(key);
			if (obj != null)
				s = obj.toString();
			return s;
		} catch (Exception e) {
			logger.error((new StringBuilder("读取")).append(path).append("文件失败！")
					.append(e.getMessage()).toString());
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}
		return null;
	}

	public static String fixedDir(String dir) {
		if (dir == null || dir.trim().equals(""))
			dir = basepath;
		if (dir == null || dir.trim().equals("")) {
			File file = new File("");
			dir = file.getAbsoluteFile().getParent();
			dir = dir.replace("\\", File.separator);
			for (dir = dir.replace("/", File.separator); dir
					.endsWith(File.separator); dir = dir.substring(0,
					dir.length() - 1))
				;
		} else {
			dir = dir.trim();
			dir = dir.replace("\\", File.separator);
			for (dir = dir.replace("/", File.separator); dir
					.endsWith(File.separator); dir = dir.substring(0,
					dir.length() - 1))
				;
		}
		File dirF = new File(dir);
		if (!dirF.exists() || !dirF.isDirectory())
			dirF.mkdirs();
		return dir;
	}

	public static File getSNFile() {
		OutputStream os = null;
		basepath = fixedDir(basepath);
		String path = (new StringBuilder(String.valueOf(basepath)))
				.append(File.separator).append("sn.properties").toString();
		File snF = new File(path);
		if (!snF.exists() || !snF.isFile()) {
			logger.warn((new StringBuilder(String.valueOf(path))).append(
					"不存在，系统初始化。").toString());
			try {
				snF.createNewFile();
				Properties config = new Properties();
				os = new FileOutputStream(snF);
				config.put("user", user);
				config.put("sn", sn);
				config.store(os, "");
			} catch (Exception e) {
				logger.error((new StringBuilder("初始化文件失败！")).append(
						e.getMessage()).toString());
				return null;
			} finally {
				if (os != null)
					try {
						os.close();
					} catch (IOException e) {
					}
			}
		}
		return snF;
	}

	public static void load() {
		InputStream is = null;
		File snF = getSNFile();
		try {
			is = new FileInputStream(snF);
			Properties config = new Properties();
			config.load(is);
			Object siteObj = config.get("user");
			if (siteObj != null)
				user = siteObj.toString();
			Object snObj = config.get("sn");
			if (snObj != null)
				sn = snObj.toString();
		} catch (Exception e) {
			logger.error((new StringBuilder("读取授权文件失败！"))
					.append(e.getMessage()).toString());
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}

	}

	public static void main(String args[]) {
		init("D:\\fds/fdsa/");
	}

}